package biz

import (
	"New-lesson-part2/custom_error"
	"New-lesson-part2/internal"
	"New-lesson-part2/model"
	"New-lesson-part2/proto/pb"
	"context"
	"errors"
	"github.com/golang/protobuf/ptypes/empty"
)

//CategoryBrand 品牌分类信息相关操作

// CreateBrandCategory 创建
func (p ProductServer) CreateBrandCategory(ctx context.Context, req *pb.CategoryBrandReq) (*pb.CategoryBrandRes, error) {
	//分类判断
	//品牌判断
	//是否存在关联
	var res pb.CategoryBrandRes //最终返回项目
	//var item model.ProductCategoryBrand                //中间关系表数据库查询项目
	var category model.CateGory                        //分类表数据库
	var brand model.Brand                              //品牌表数据库
	r := internal.DB.First(&category, req.Category.Id) //根据传入的关联信息查询category是否存在
	if r.RowsAffected == 1 {
		return nil, errors.New(custom_error.CategoryDataIsExists)
	}
	r = internal.DB.First(&brand, req.Brand.Id)
	if r.RowsAffected == 1 {
		return nil, errors.New(custom_error.BrandAlreadyExits)
	}
	create := internal.DB.Save(&model.ProductCategoryBrand{
		BrandID:    req.Brand.Id,
		CategoryID: req.Category.Id,
		Brand: model.Brand{
			Name: req.Brand.Name,
			Logo: req.Brand.Logo,
		},
		Category: model.CateGory{
			Name:             req.Category.Name,
			Level:            req.Category.Level,
			ParentCategoryID: req.Category.ParentCategoryId,
		},
	})
	if create.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryBrandDataCreateFailed)
	}
	resBrandMod2pb := ConvertBrandModel2pb(brand)
	resCategory2pb := ConvertCategoryModel2pb(category)
	res.Brand = resBrandMod2pb
	res.Category = resCategory2pb
	return &res, nil
}

// CategoryBrandList 分页查询.查询所有集合类型??有啥意义?
func (p ProductServer) CategoryBrandList(ctx context.Context, req *pb.PagingReq) (*pb.CategoryBrandListRes, error) {
	var categoryBrandMod []model.ProductCategoryBrand     //*pb.CategoryBrandRes
	var createToBrandIntersection pb.CategoryBrandListRes //CategoryBrandRes
	var categoryBrandList []*pb.CategoryBrandRes          // 构成的基本元素是CategoryBrandRes
	var count int64
	myPaging := internal.MyPaging(req.PageNo, req.PageSize)
	r := internal.DB.Scopes(myPaging).Count(&count).Find(&categoryBrandMod)
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryBrandDoesNotExist)
	}
	for _, i := range categoryBrandMod {
		categoryBrandList = append(categoryBrandList, ConvertProductCategoryBrand2pb(i))
	}
	createToBrandIntersection.ItemList = categoryBrandList
	createToBrandIntersection.Total = int32(count)
	return &createToBrandIntersection, nil

}

// GetCategoryBrandList 根据categoryId 查询brand
func (p ProductServer) GetCategoryBrandList(ctx context.Context, req *pb.CategoryItemReq) (*pb.BrandRes, error) {
	var res pb.BrandRes //查询啥就定义啥
	var category model.CateGory
	var itemList []model.ProductCategoryBrand
	var itemListRes []*pb.BrandItemRes
	r := internal.DB.First(&category, req.Id) //根据传入的id查找是否存在category相关数据记录
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryDoesNotExist)
	}
	r = internal.DB.Preload("Brand").Where(&model.ProductCategoryBrand{CategoryID: req.Id}).Find(&itemList)
	if r.RowsAffected > 0 {
		res.Total = int32(r.RowsAffected)
		for _, i := range itemList {
			itemListRes = append(itemListRes, &pb.BrandItemRes{
				Id:   i.BrandID,
				Name: i.Brand.Name,
				Logo: i.Brand.Logo,
			})
		}
	}
	res.ItemList = itemListRes
	return &res, nil
}

// GetBrandCategoryList 根据brand信息查询category信息
func (p ProductServer) GetBrandCategoryList(ctx context.Context, req *pb.BrandItemReq) (*pb.CategoryRes, error) {
	var res pb.CategoryRes
	var cateMOdList []model.CateGory
	var cateListRes []*pb.CategoryItemRes
	var count int64
	r := internal.DB.First(&model.ProductCategoryBrand{BrandID: req.Id})
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.BrandDoesNotExist)
	}
	r = internal.DB.Where(&model.ProductCategoryBrand{BrandID: req.Id}).Count(&count).Find(&cateMOdList)
	if r.RowsAffected > 1 {
		for _, i := range cateMOdList {
			cateListRes = append(cateListRes, ConvertCategoryModel2pb(i))
		}
	}
	res.Total = int32(count)
	res.CategoryList = cateListRes
	return &res, nil
}

// DeleteCategoryBrand 删除
func (p ProductServer) DeleteCategoryBrand(ctx context.Context, req *pb.CategoryBrandReq) (*empty.Empty, error) {
	var cb model.ProductCategoryBrand
	r := internal.DB.First(&cb)
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryBrandDoesNotExist)
	}
	tx := internal.DB.Delete(&model.ProductCategoryBrand{}, req.Id)
	if tx.Error != nil {
		return nil, errors.New(custom_error.CategoryToBrandSystemError)
	}
	return &empty.Empty{}, nil
}

// UpdateCategoryBrand 更新
func (p ProductServer) UpdateCategoryBrand(ctx context.Context, req *pb.CategoryBrandReq) (*empty.Empty, error) {
	var cb model.ProductCategoryBrand
	r := internal.DB.Where(&model.ProductCategoryBrand{}, req.Id).First(&cb)
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryBrandDoesNotExist)
	}
	cb.Brand.ID = req.Brand.Id
	cb.Brand.Name = req.Brand.Name
	cb.Brand.Logo = req.Brand.Logo
	cb.Category.ID = req.Category.Id
	cb.Category.Name = req.Category.Name
	cb.Category.Level = req.Category.Level
	cb.Category.ParentCategoryID = req.Category.ParentCategoryId

	r = internal.DB.Save(&cb)
	if r.RowsAffected < 1 {
		return nil, errors.New(custom_error.CategoryBrandDataCreateFailed)
	}
	if r.Error != nil {
		return nil, errors.New(custom_error.CategoryToBrandSystemError)
	}
	return &empty.Empty{}, nil
}

func ConvertProductCategoryBrand2pb(brand model.ProductCategoryBrand) *pb.CategoryBrandRes {
	cb := pb.CategoryBrandRes{
		Id: 0,
		Brand: &pb.BrandItemRes{
			Id:   brand.BrandID,
			Name: brand.Brand.Name,
			Logo: brand.Brand.Logo,
		},
		Category: &pb.CategoryItemRes{
			Id:               brand.CategoryID,
			Name:             brand.Category.Name,
			ParentCategoryId: brand.Category.ParentCategoryID,
			Level:            brand.Category.Level,
		},
	}
	return &cb
}
